package com.sz.virtualbank.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 * 
 * @author Claude
 */
@Slf4j
public class JwtUtil {
    
    /**
     * 密钥 - 至少32个字节以满足HS256算法的要求
     */
    private static final String SECRET = "szVirtualBankSecretKey_ForHS256_MinLength32Bytes";
    
    /**
     * 生成安全密钥
     */
    private static final SecretKey KEY = Keys.hmacShaKeyFor(SECRET.getBytes());
    
    /**
     * 过期时间（毫秒）：2小时
     */
    private static final long EXPIRE_TIME = 2 * 60 * 60 * 1000;
    
    /**
     * 生成Token
     * 
     * @param userId 用户ID
     * @return Token
     */
    public static String generateToken(Long userId) {
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + EXPIRE_TIME);
        
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(now)
                .setExpiration(expireDate)
                .signWith(KEY)
                .compact();
    }
    
    /**
     * 解析Token
     * 
     * @param token Token
     * @return Claims
     */
    public static Claims parseToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("JWT解析异常：{}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 验证Token是否有效
     * 
     * @param token Token
     * @return 是否有效
     */
    public static boolean validateToken(String token) {
        if (StringUtils.isBlank(token)) {
            return false;
        }
        
        try {
            Claims claims = parseToken(token);
            return claims != null && !claims.getExpiration().before(new Date());
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 从Token中获取用户ID
     * 
     * @param token Token
     * @return 用户ID
     */
    public static Long getUserIdFromToken(String token) {
        Claims claims = parseToken(token);
        if (claims == null) {
            return null;
        }
        return claims.get("userId", Long.class);
    }
}
